﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace team33_ass3
{
    class Enemy : GameObject
    {
        Player goal;
        int id;
        AStar aStar;
        Vector3 waypoint;
        List<MapBlock> path;
        Map map;

        public Enemy(Model model, Vector3 pos, Player goal, int id, AStar aStar, Map map)
            : base(model, pos)
        {
            this.goal = goal;
            this.id = id;
            this.aStar = aStar;
            scaleValue = 0.05f;
            this.map = map;
            getNewWayPoint();
        }

        public int getId()
        {
            return id;
        }

        public void Update(bool collided, GameTime gameTime)
        {
            if (atWayPoint())
            {
                float speed = 0.1f;
                Vector3 direction = waypoint - this.position;
                direction.Normalize();
                double time = gameTime.ElapsedGameTime.TotalMilliseconds;

                if (this.position != goal.position)
                {
                    this.position += (direction * speed * (float)time);
                }
            }
            // at the waypoint, need new waypoint
            else
            {
                getNewWayPoint();
            }
            
            
        }

        private void getNewWayPoint()
        {
            path = aStar.getPath(this.position, goal.position);
            if (path.Count > 0)
            {
                MapBlock tmp = path.ElementAt(0);
                waypoint = new Vector3(tmp.getRealX(), 0, tmp.getRealY());
            }
        }

        private bool atWayPoint()
        {
            return (map.getBlock(this.position) != map.getBlock(waypoint)) && closeEnough();
        }

        private bool closeEnough()
        {
            float x = Math.Abs(this.position.X - waypoint.X);
            float y = Math.Abs(this.position.Z - waypoint.Z);

            return !(x == 0 && y == 0);
        }

    }
}
